package Server;

import Data.FriendListData;
import Data.RegisterData;
import Email.GetCaptcha;
import Email.ManageCaptcha;
import MyInterfaces.MassageType;
import Data.event;
import Search.CheckDuplicate;
import Search.UserInitStage;

import java.io.*;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import Email.*;

public class RegisterServer {
    static String sql = "insert into userinformation(emailNumber,userPwd,id,avatar,userNickName) values (?,?,?,?,?);";
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";
    private ServerSocket serverSocket;
    private Socket socket;

    public RegisterServer(ServerSocket serverSocket, Socket socket) {
        this.serverSocket = serverSocket;
        this.socket = socket;
    }

    public boolean register(event massage) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("连接数据库");
        Connection Conn = DriverManager.getConnection(url, user, password);
        //需要先判断邮箱是否已经有了
        PreparedStatement operation = null;
        String presql="select *from userinformation where emailNumber=?;";
        RegisterData registerData= (RegisterData) massage.getT();

        operation=Conn.prepareStatement(presql);
        operation.setString(1,registerData.getEmail());
        ResultSet resultSet=operation.executeQuery();
        if (resultSet.next())
        {
            //说明已经有该邮箱注册的账号
            event returnmassage=new event();
            returnmassage.setType(MassageType.Return_Register_Fail);
            ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
            writer.writeObject(returnmassage);
            writer.flush();
            return false;
        }

        GetCaptcha getCaptcha = new GetCaptcha();

        System.out.println(sql);
        operation = null;
        operation = Conn.prepareStatement(sql);

        //得到该验证码
        String yzm = ManageCaptcha.GetcaptchaByEmail(registerData.getEmail(),new Date()).getCaptcha();

        String captcha=registerData.getCaptcha();
        String zcemail=registerData.getEmail();
        String userPwd=registerData.getUserPwd();
        String md5=getMD5(userPwd);
        CheckDuplicate check=new CheckDuplicate();

        GetId getId = new GetId();
        long newid = getId.nextId();
        String ID = String.valueOf(newid);
        ID=ID.substring(ID.length()-9);

        boolean is=check.check(ID,1);
        while(!is)
        {
            getId = new GetId();
            newid = getId.nextId();
            ID = String.valueOf(newid);
            ID=ID.substring(ID.length()-9);

            is=check.check(ID,1);
        }

        if(!yzm.equals(captcha))
        {
            //如果验证码不一样那么就返回注册失败的消息
            event returnmassage=new event();
            returnmassage.setType(MassageType.Return_Register_Fail);
            ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
            writer.writeObject(returnmassage);
            writer.flush();
            return false;
        }

        //如果相等需要销毁验证码
        ManageCaptcha.RemoveCaptchaByEmail(zcemail);
        //设置头像,完成复制头像
        String idpath="F:\\qqserverfile\\avatar"+"\\"+ID+".jpg";
        String path="F:\\qqserverfile\\avatar\\1.jpg";
        System.out.println(idpath);
        File idfile=new File(idpath);
        File file=new File(path);
        FileOutputStream fileOutputStream=new FileOutputStream(idpath);
        byte[] t=new byte[(int) file.length()];
        FileInputStream fileInputStream=new FileInputStream(file);
        fileInputStream.read(t);
        fileOutputStream.write(t);
        //关闭流
        fileOutputStream.close();
        fileInputStream.close();
    //    fileOutputStream.write();
        //昵称
        operation.setString(1, registerData.getEmail());
        operation.setString(2, md5);
        operation.setString(3, ID);
        operation.setString(4,idpath);
        operation.setString(5, registerData.getUserNumber());

    //    PreparedStatement newoperation=Conn.prepareStatement()
        int k = operation.executeUpdate();
        if (k > 0) {
            Conn.close();
            ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
            event returnmassage=new event();
            returnmassage.setType(MassageType.Return_Register_Success);
            //要发送注册的消息过去
            UserInitStage userInitStage=new UserInitStage(ID);
            FriendListData friendListData=userInitStage.userInformation();
            returnmassage.setT(friendListData);
            System.out.println(ID);
            writer.writeObject(returnmassage);
            writer.flush();

            System.out.println("接受客户端发送的消息");
            ChatServer chatServer=new ChatServer(socket,ID);

            //开启一个线程用来接收消息
            new Thread(chatServer).start();
            ManageClientConnectionServerThread.addThread(ID,chatServer);
        } else {
            ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
            event returnmassage=new event();
            returnmassage.setType(MassageType.Return_Register_Fail);
            writer.writeObject(returnmassage);
            writer.flush();
        }
        return true;
    }

    public String getMD5(String str) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        return new BigInteger(1, md.digest()).toString(16);
    }
}
